package com.wiki.gds.user.provider.security.oauth2.config;

import com.wiki.gds.base.database.mutidatasource.annotion.DataSource;
import com.wiki.gds.base.security.common.exception.WebResponseExceptionTranslator;
import com.wiki.gds.base.security.common.integration.authenticator.IntegrationAuthenticationFilter;
import com.wiki.gds.user.provider.security.oauth2.core.service.IntegrationUserDetailsService;
import com.wiki.gds.user.provider.security.oauth2.exception.CustomWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;


@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {


    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private WebResponseExceptionTranslator webResponseExceptionTranslator;

    @Autowired
    IntegrationAuthenticationFilter integrationAuthenticationFilter;

    @Autowired
    private IntegrationUserDetailsService integrationUserDetailsService;

    @Autowired
    private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String finalSecret = "{noop}123456";
        clients.inMemory().withClient("gds-admin")
                .resourceIds("user","shop","admin","member")
                .authorizedGrantTypes("client_credentials", "refresh_token","password")
                .scopes("select")
                .authorities("oauth2")
                .secret(finalSecret).refreshTokenValiditySeconds(60);

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .tokenServices(tokenServices())
//                .pathMapping("/oauth/token", "/oauth2/token")
              //.accessTokenConverter(jwtAccessTokenConverter())
                .exceptionTranslator(webResponseExceptionTranslator)
                .authenticationManager(authenticationManager)
                .userDetailsService(integrationUserDetailsService)
                .reuseRefreshTokens(false)
                .exceptionTranslator(customWebResponseExceptionTranslator)
                .tokenEnhancer(new CustomTokenEnhancer())

                 ;}
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {

        //允许表单认证
                  oauthServer.allowFormAuthenticationForClients()
                          .tokenKeyAccess("isAuthenticated()")
                          .checkTokenAccess("permitAll()")

                  ;
    }
    @Bean
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setAccessTokenValiditySeconds(7200);
        defaultTokenServices.setRefreshTokenValiditySeconds(72000);
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setReuseRefreshToken(false);
        defaultTokenServices.setTokenStore(getRedisTokenStore());
        defaultTokenServices.setTokenEnhancer(new CustomTokenEnhancer());
        return defaultTokenServices;
    }

    @Bean
    public RedisTokenStore getRedisTokenStore(){

        RedisTokenStore redisTokenStore=new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix("gds-sso:");
        return redisTokenStore;
    }


//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
//        jwtAccessTokenConverter.setSigningKey("gds-cloud");
//        return jwtAccessTokenConverter;
//    }


}
